///<reference path='./Cat.ts'/>
///<reference path='./Brush.ts'/>
///<reference path='./UILayer.ts'/>
///<reference path='./Enemy.ts'/>
///<reference path='./utils/BulkLoader.ts'/>
///<reference path='./utils/ImageLoader.ts'/>
// import { Cat, PositionGroup, PresetPointData } from "./Cat";
// import { Brush } from "./Brush";
// import { UILayer } from "./UILayer";
// import { Enemy } from "./Enemy"

declare var $api:any;
class App {
    public static loadManager: BulkLoader;
    private _stage: lg.Stage;
    private _resSuffix: string = "@2x";

    public static curScore: number;
    private _scoreText: lg.Text;
    public isDebug: boolean = true;
    private _brush: Brush;
    private _cat: Cat;
    private _lastEnemyPoint: lg.Point;
    private _lastEnemy: Enemy;
    private _coefficientNum: number = 0;
    private _finishCount: number = 1;
    private _lastBrushRotation: number;
    private _touchUp: lg.Bitmap;
    private _touchDown: lg.Bitmap;

    public static lasetPositionGroup: PositionGroup;
    private _upToothLayer: lg.Container;
    private _downToothLayer: lg.Container;

    private boomFlameSheet: lg.SpriteSheet;
    private boom: lg.Sprite;





    private resetGame() {
        App.curScore = 0;
        // this._brush.visible=false;
        this._cat._skin.gotoAndStop(0);
        this.initBrush();
        this._brush.visible = false;
        this._touchDown.visible = false;
        this._touchUp.visible = false;;
        setTimeout(() => {
            this.initBrush();
            this._brush.visible = true;

        }, 500
        );
        setTimeout(() => this.initData(), 2000);

        for (var i = 0; i < this._enemys.length; i++) {
            let e: Enemy = this._enemys[i];
            e.parent.removeChild(e);

            this.boomFunc(e);
        }
        if (this._lastEnemy) {
            this._lastEnemy.parent.removeChild(this._lastEnemy);
            this._lastEnemy = null;
            this.boomFunc(this._lastEnemy);
        }
    }
    private boomFunc(e) {
        console.log("e", e.x, e.y);
        var p = this._stage.localToGlobal(e.x, e.y)
        console.log("p", p.x, p.y);
        this.boom.x = p.x;
        this.boom.y = p.y;
        this.boom.play();
        this.boom.visible = true;
    }
    public setScore(): void {
        App.curScore++;
        if (App.curScore == 100) {
            this.resetGame()

        }
        // this._gameStar.setScore(App.curScore);
        // console.log(App.curScore);
        this.changeScore(App.curScore)

        // if (App.curScore >= this._finishCount * this._coefficientNum) {
        //     this._finishCount++;
        //     this.nextEnemyFight();
        // }

    }
    public changeScore(v)
    {
        App.curScore=v;
        this._scoreText.text = v + "分";
    }
    constructor() {
        this.boomFlameSheet = new lg.SpriteSheet({ images: ["../res/assets/images/boom.png"], frames: [[0, 0, 70, 70, 0, 62.150000000000006, 20.549999999999997], [0, 0, 70, 70, 0, 62.150000000000006, 20.549999999999997], [70, 0, 105, 100, 0, 79.15, 32.55], [70, 0, 105, 100, 0, 79.15, 32.55], [0, 100, 141, 113, 0, 100.15, 43.55], [0, 100, 141, 113, 0, 100.15, 43.55], [0, 213, 166, 139, 0, 109.15, 51.55], [0, 213, 166, 139, 0, 109.15, 51.55], [0, 352, 91, 47, 0, 27.150000000000006, 47.55], [0, 352, 91, 47, 0, 27.150000000000006, 47.55]] });
        this.boom = new lg.Sprite(this.boomFlameSheet);
        lg.Ticker.addEventListener("tick", () => {

            if (this.boomFlameSheet.getNumFrames(this.boomFlameSheet.getAnimations()[0]) == this.boom.currentFrame + 1) {

                //播放完时
                this.boom.gotoAndStop(1);
                this.boom.visible = false;
            }

        })


        this._stage = new lg.Stage("canvasElement");
        // this._stage.addEventListener("click", (e) => {
        //     if (this.isDebug) this.setScore();
        // });


        App.loadManager = BulkLoader.getInstance();

        // App.loadManager.on("complete", this.handleComplete, this);
        // App.loadManager.loadManifest([

        App.loadManager.addEventListener(LoaderEvent.LOAD_COMPLETE, this.handleComplete, this);
        // { id: "back-button", src: "res/assets/images/back-button" + this._resSuffix + ".png" },
        var loadFiles = [
            { id: "background", src: "../res/assets/images/back-ground.png" },
            { id: "green", src: "../res/assets/images/left-up-green" + this._resSuffix + ".png" },
            { id: "purple", src: "../res/assets/images/left-down--purple" + this._resSuffix + ".png" },
            // { id: "music-button", src: "res/assets/images/music-button" + this._resSuffix + ".png"},
            { id: "bubble", src: "../res/assets/images/bubble.png" },
            { id: "progress_bg", src: "../res/assets/images/progress_bg.png" },
            { id: "progress_bar", src: "../res/assets/images/progress_bar.png" },
            { id: "btnback", src: "../res/assets/images/btnback.png" },
            { id: "btnmusic", src: "../res/assets/images/btnmusic.png" },
            { id: "washbasin", src: "../res/assets/images/washbasin" + this._resSuffix + ".png" },
            { id: "toothDown", src: "../res/assets/images/tooth-down" + this._resSuffix + ".png" },
            { id: "toothUp", src: "../res/assets/images/tooth-up" + this._resSuffix + ".png" }
        ]

        // ]);
        for (var j = 0; j < loadFiles.length; j++) {
            var o = loadFiles[j]
            App.loadManager.addFile(new ImageLoader(o.src), o.id);
            // console.log(o.id)
        }
        App.loadManager.load();


        this._scoreText = new lg.Text("0分", "40px Arial", "#FF00FF");
        lg.Ticker.addEventListener("tick", this._stage);
    }
    private handleComplete() {
        App.curScore = 0;
        this._stage.addChild(new lg.Bitmap(App.loadManager.getImage("background")));
        var canvas: HTMLCanvasElement = <HTMLCanvasElement>this._stage.canvas;
        this._scoreText.x = canvas.width >> 1;
        this._scoreText.textAlign = "center";
        //console.log( this._scoreText.x);
        this._scoreText.y = 246;
        // this._scoreText.color = "#000000";

        this._stage.addChild(this._scoreText);

        this._cat = new Cat();
        this._stage.addChild(this._cat);
        this._cat.y = canvas.height;
        this._cat.x = canvas.width >> 1;
        var washbasin: lg.Bitmap = new lg.Bitmap(App.loadManager.getImage("washbasin"));
        this._stage.addChild(washbasin);
        washbasin.x = canvas.width - washbasin.image.width >> 1;
        washbasin.y = canvas.height - washbasin.image.height;
        this._brush = new Brush();
        this.initBrush();
        this._stage.addChild(this._brush);
        // this._enemyLayer = new lg.Container();
        // this._stage.addChild(this._enemyLayer);
        this.createBubbles();
        this._bubblesLayer.visible = false;




        setInterval(() => this.loop(), 500);
        setTimeout(() => this.initData(), 2000);


        this.touchInit();

        this._stage.addChild(new UILayer);
        this._stage.addChild(this.boom)

    }
    private touchInit() {
        this._upToothLayer = new lg.Container();
        this._stage.addChild(this._upToothLayer);
        this._downToothLayer = new lg.Container();
        this._stage.addChild(this._downToothLayer);
        this._upToothLayer.name = "upToothLayer";
        this._downToothLayer.name = "downToothLayer";
        this._touchUp = new lg.Bitmap(App.loadManager.getImage("toothUp"));

        this._touchDown = new lg.Bitmap(App.loadManager.getImage("toothDown"));
        this._touchDown.x = 251;
        this._touchDown.y = 785;
        this._downToothLayer.addChild(this._touchDown);
        this._touchUp.x = 251;
        this._touchUp.y = 659;
        this._upToothLayer.addChild(this._touchUp);
        this._touchDown.visible = false;
        this._touchUp.visible = false;;
        // console.log("wwwwwwwww")
    }
    private initBrush() {
        this._brush.x = 165;
        this._brush.name = "brush"
        if (this._brush._skin) {
            this._brush._skin.gotoAndStop(1);
            this._brush.yoyo(false);
        }
        this._brush.scaleX = 1;
        this._brush.scaleY = 1;
        this._brush.y = 850;
        this._brush.rotation = 90;

    }
    private initData() {
        var c: HTMLCanvasElement = <HTMLCanvasElement>this._stage.canvas;
        this._cat.initData();
        this._coefficientNum = 0;
        this._finishCount = 1;
        this._brush.x = 135;

        this._brush.y = 1121;
        this._brush.scaleX = 1;
        this._brush.scaleY = 1;
        this._brush.rotation = -90;
        this._brush.visible = true;
        this._brush._skin.play();
        this._brush.yoyo(true);
        TweenMax.to(this._brush, 2, { scaleX: 0.8, scaleY: 0.8, rotation: 720 + this._lastBrushRotation })

        this._enemys = new Array<Enemy>();

        // this.createEmeny();  
        // this.createEmeny();
        // this.createEmeny();
        // this.createEmeny();
        // this.createEmeny();
        // var enemys = [
        //     { id: 0, time: 0 },
        //     { id: 1, time: 2000 },
        //     { id: 2, time: 8000 },
        // ]
        // console.log("bbbbbbbbbbbbbbbbbbbb")
        var data: Array<any> = new Array<any>();
        var enemys = window["enemysData"];
        var d = this.getData();
        for (var i = 0; i < enemys.length; i++) {
            var ed = enemys[i];
            var enemy: Enemy = this.createEmenyByID(ed.id);
            enemy.visible = false;
            var tempDisplay=true;
            
            if (d) {
                if (d[i].display == false) {
                    console.log(i, "已在上次被击杀")
                    tempDisplay=false;
                }
                else {
                    this.showEnemy(enemy, ed.time);
                }
            }else {
                    this.showEnemy(enemy, ed.time);
                }

            //深度设置
            var depths = window["depths"];
            var depth = depths[i];
            // var lastIndex=this._stage.getNumChildren()-1;
            // this._stage.setChildIndex(this._brush,lastIndex-depth.brush);
            // this._stage.setChildIndex(this._touchUp,lastIndex-depth.toothUp);
            // this._stage.setChildIndex(this._touchDown,lastIndex-depth.toothDown);
            // this._stage.setChildIndex(enemy,lastIndex-depth.enmey);
            // console.log(i, depth)
            this.sortObjects(depth);
            if (depth.direction == "up") {
                if (depth.toothUp > depth.enmey) {
                    // console.log(this._upToothLayer.getNumChildren()+"aaaaaaaaaaaaaaaaaaaaa")
                    this._upToothLayer.addChildAt(enemy, this._upToothLayer.getNumChildren())
                    // .addChild(enemy);
                } else {
                    this._upToothLayer.addChildAt(enemy, 0)
                }
            }
            else if (depth.direction == "down") {
                if (depth.toothDown > depth.enmey) {
                    // console.log(i, "前方")
                    this._downToothLayer.addChildAt(enemy, this._downToothLayer.getNumChildren())
                    // .addChild(enemy);
                } else {
                    this._downToothLayer.addChildAt(enemy, 0)
                }
            }
            data.push({ index: i, display: tempDisplay })
            //深度设置

        }
        this.savaData(data);

        this._coefficientNum = 100 / this._enemys.length;

        this._stage.addChild(this._brush);
        this._bubblesLayer.visible = true;


        this._touchDown.visible = true;
        this._touchUp.visible = true;

        // this._stage.addChild(this._enemyLayer);
    }
    private savaData(data: any) {
        var dj = JSON.stringify(data);
        if($api)
        {
           $api.setStorage("data", dj);
        }
        else
        {
            localStorage.setItem("data", dj);
        }
    }
    private getData(): Array<any> {
        var dj;
        if($api)
        {
            dj = $api.getStorage("data");
        }
        else
        {
             dj =localStorage.getItem("data");
        }

        return dj?JSON.parse(dj):null;

    }
    private showEnemy(enemy: Enemy, time: number): void {
        setTimeout(() => {

            enemy.visible = true
        }, time)
    }
    private nextEnemyFight(pos, isremove) {
        var data = this.getData();
        data[pos].display = !isremove;
        this.savaData(data);
        // if (this._lastEnemy) this._lastEnemy.parent.removeChild(this._lastEnemy);
        this._lastEnemy = this._enemys[pos];
        if (isremove) {
            this._lastEnemy.parent.removeChild(this._lastEnemy);
            this.boomFunc(this._lastEnemy);
            return;
        }
        this._lastEnemyPoint = new lg.Point(this._lastEnemy.x, this._lastEnemy.y);
        var pg: PositionGroup = parseInt(this._lastEnemy.name);
        App.lasetPositionGroup = pg;
        
        this._lastBrushRotation = this._brush.rotation;


        //深度设置
        var depths = window["depths"];
        var depth = depths[pg];

        // if (depth.brush > depth.enmey) {
        //     this._bottomToothLayer.addChild(this._brush);
        // } else {
        //     this._coverToothLayer.addChild(this._brush);
        // }
        this.sortObjects(depth);
        if (depth.direction == "up") {
            if (depth.toothUp < depth.enmey) {
                this._upToothLayer.addChildAt(this._brush, 0);
                // .addChild(enemy);
            } else {
                this._upToothLayer.addChildAt(this._brush, this._upToothLayer.getNumChildren())
            }
        }
        else if (depth.direction == "down") {
            if (depth.toothDown < depth.enmey) {

                this._downToothLayer.addChildAt(this._brush, 0)
                // .addChild(enemy);
            } else {
                this._downToothLayer.addChildAt(this._brush, this._downToothLayer.getNumChildren())
            }
        }
        //深度设置
        this._lastEnemy.start();
        TweenMax.to(this._brush, 1, { x: this._lastEnemyPoint.x, y: this._lastEnemyPoint.y });
    }
    private sortObjects(configData): void {
        // console.log("_upToothLayer",this._upToothLayer.getNumChildren());
        // console.log("_downToothLayer",this._downToothLayer.getNumChildren())
        // console.log("_brush",this._brush.getNumChildren())
        var sort = [
            this._stage.getChildIndex(this._upToothLayer),
            this._stage.getChildIndex(this._downToothLayer),
            this._stage.getChildIndex(this._brush)
        ];
        sort.sort(this.sortUpdate);
        // console.log(sort+"here")
        //{toothUp:1,brush:3,toothDown:2,enmey:0,id:0,direction:"up"},
        var config = [
            { obj: this._brush, depth: configData.brush },
            { obj: this._downToothLayer, depth: configData.toothDown },
            { obj: this._upToothLayer, depth: configData.toothUp }
        ];
        config.sort(this.sortUpdateConfig);
        // console.log(config)
        for (var i = 0; i < config.length; i++) {
            var obj = config[i].obj;
            this._stage.setChildIndex(obj, sort.shift());
            // console.log(obj.name,config[i].depth)
        }
    }
    private sortUpdateConfig(a, b) {
        return a.depth - b.depth;
    }
    private sortUpdate(a, b) {
        return b - a;
    }

    private tickHandler(e) {
        this.loop();
    }
    private loop() {
        if (!this._lastEnemy) return;
        if (this._enemys.length == 0 && this._lastEnemy._hp == 0) {
            //游戏结束
            this.resetGame();
            return;
        }


        // console.log(this._lastEnemy._hp+"looop")
        if (this._lastEnemy._hp == 0) {

            this._finishCount++;
            // this.nextEnemyFight();
        }
    }
    private _enemys: Array<Enemy>;
    private _enemysString = [
        "purple",
        "green"
    ];
    // private _enemyLayer: lg.Container;
    private createEmeny() {
        let enemy: Enemy = new Enemy(App.loadManager.getImage(this._enemysString[Math.floor(Math.random() * 1.9)]));
        enemy.scaleX = Math.random() < 0.5 ? 1 : -1;
        enemy.regX = enemy.getBounds().width >> 1;
        enemy.regY = enemy.getBounds().height >> 1;
        var scale = enemy.scaleX * 0.5;
        // this._stage.addChild(enemy);
        TweenMax.to(enemy, Math.random() * 2 + 1, { scaleX: scale, scaleY: 0.5, repeat: -1, yoyo: true });

        var p: lg.Point = new lg.Point();
        var ppd: PresetPointData = this._cat.getEnemyPresetPointDataByPreset();
        p = this._cat.localToGlobal(ppd.point.x, ppd.point.y);
        //var p = this._cat.getEnemyPointByPreset();
        enemy.x = p.x
        enemy.y = p.y;
        enemy.name = ppd.positionGroup.toString();
        this._enemys.push(enemy);
    }

    private createEmenyByID(v: PositionGroup): Enemy {
        let enemy: Enemy = new Enemy(App.loadManager.getImage(this._enemysString[Math.floor(Math.random() * 1.9)]));
        enemy.scaleX = Math.random() < 0.5 ? 1 : -1;
        enemy.regX = enemy.getBounds().width >> 1;
        enemy.regY = enemy.getBounds().height >> 1;
        var scale = enemy.scaleX * 0.5;
        // this._stage.addChild(enemy);
        TweenMax.to(enemy, Math.random() * 2 + 1, { scaleX: scale, scaleY: 0.5, repeat: -1, yoyo: true });

        var p: lg.Point = new lg.Point();
        var ppd: PresetPointData = this._cat.getEnemyPresetPointDataByPositionGroup(v);
        p = this._cat.localToGlobal(ppd.point.x, ppd.point.y);
        //var p = this._cat.getEnemyPointByPreset();
        enemy.x = p.x
        enemy.y = p.y;
        enemy.name = ppd.positionGroup.toString();
        enemy.initData();
        this._enemys.push(enemy);
        return enemy;
    }


    private _bubblesLayer: lg.Container;
    private createBubbles() {
        this._bubblesLayer = new lg.Container();
        this._stage.addChild(this._bubblesLayer);
        for (var i = 0; i < 10; i++) {
            let bubble: lg.Bitmap = new lg.Bitmap(App.loadManager.getImage("bubble"));
            var c: HTMLCanvasElement = <HTMLCanvasElement>this._stage.canvas;
            bubble.x = c.width * Math.random();
            bubble.y = c.height * Math.random();
            bubble.regX = bubble.getBounds().width >> 1;
            bubble.regY = bubble.getBounds().height >> 1;
            //TweenMax.to(bubble,Math.random()*25+13,{scaleX:Math.random()*3,scaleY:Math.random()*3,alpha:0,repeat:-1,y:300});
            var s = Math.random() * 3;
            TweenMax.to(bubble, Math.random() * 5 + 5, { scaleX: s, scaleY: s, repeat: -1, alpha: Math.random(), rotation: Math.random() * 180, yoyo: true })
            this._bubblesLayer.addChild(bubble);
        }
    }
}

// new App();

